extends CharacterBody2D


@export var speed = 50.0
@export var friction = 50.0
@export var face = "Down"
@onready var animations = $Animations

@onready var stateMachine = $StateMachine

var interactables = []
var data


func setPosAndFace(pos, face):
	position = pos
	animations.play("Idle" + face)


func setSpriteFrames(spriteFrames):
	animations.sprite_frames = ResourcePreload.resources[spriteFrames]


func _ready():
	add_to_group(Consts.GROUP_PLAYER)
	
	interactables = []
	stateMachine.addState(Consts.playerStateNormal)
	

func _exit_tree():
	remove_from_group(Consts.GROUP_PLAYER)


func _physics_process(delta):
	processZIndex()
	stateMachine.run(delta)
	
	
func processZIndex():
	z_index = int(position.y)


func _on_interact_area_area_entered(area):
	if area is Interactable:
		interactables.append(area)
		print("_on_interact_area_area_entered ", interactables.size())


func _on_interact_area_area_exited(area):
	if area is Interactable:
		interactables.erase(area)
		area.onExitInteractableArea()
		print("_on_interact_area_area_exited ", interactables.size())
	

func processMove(delta):
	var horizontalInput = Input.get_axis("ui_left", "ui_right")
	var verticalInput = Input.get_axis("ui_up", "ui_down")
	var inputDir = Vector2(horizontalInput, verticalInput).normalized()
	if inputDir.y < 0:
		face = "Up"
	if inputDir.y > 0:
		face = "Down"
	if inputDir.x < 0:
		face = "Left"
	if inputDir.x > 0:
		face = "Right"
	
	if inputDir.length() > 0:
		velocity = inputDir * speed
		animations.play("Walk" + face)
	else:
		velocity = velocity.lerp(Vector2.ZERO, friction * delta) 
		animations.play("Idle" + face)

	move_and_slide()


func processInteract():
	if interactables.size() <= 0: return
	
	if Input.is_action_just_pressed("Interact"):
		var interactTarget = interactables[0]
		interactTarget.interact()



